/**
 * axios二次封装
 */
import router from '../router/index.ts'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import storage from './storage'

const TOKEN_INVALID = 'token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'

// const instance = axios.create({
//     baseURL: "/api",
//     timeout: 8000,
// })

const instance = axios.create({
  baseURL: 'http://127.0.0.1:8088',
  // baseURL: 'http://139.159.141.206:8088',
  timeout: 8000
})

// 配置请求拦截器
instance.interceptors.request.use(req => {
  req.headers['Authorization'] = storage.getItem('token')
  return req
})

// 配置响应拦截器
instance.interceptors.response.use(res => {
  const { code, msg } = res.data
  if (res.headers['authorization']) {
    const token = res.headers['authorization']
    storage.setItem('token', token)
  }
  if (code === '200') {
    return res.data
  } else if (code === '204') {
    return res.data
  } else if (code === '666') {
    ElMessage.error(TOKEN_INVALID)
    setTimeout(() => {
      router.push('/login')
    }, 1500)
  } else if (code === '888') {
    return res.data
  } else {
    ElMessage.error(msg || NETWORK_ERROR)
    if (!msg) {
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    }
    return Promise.reject(msg || NETWORK_ERROR)
  }
})

/**
 *  请求核心函数
 * @param {*} options 请求配置
 * @returns
 */
function request(options: any) {
  options.method = options.method || 'GET'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }
  return instance(options)
}

export default request
